<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class GiftLibrary extends BaseModel
{
    protected $table = 'gift_library';
    protected $giftLuckPool_table = 'gift_luck_pool';
    protected $giftStreamTable = 'gift_stream';
    protected $user = 'user';
    protected $colorGiftPoolConfigTable = 'color_gift_pool_config';
    protected $giftTable = 'gift_library';
    protected $colorGiftMaxConfigTable = 'color_gift_rate_max_config';//彩蛋礼物上限配置
    protected $colorGiftStream = 'color_gift_rate_award_stream';//彩蛋礼物流水
    protected $colorGifColorPoolTable = 'color_gift_pool';//彩蛋礼物奖池表
    protected $colorGiftPoolRateBannerTable = 'color_gift_pool_rate_banner';
    protected $colorGiftWhiteTable = 'color_gift_white_config';//彩蛋白名单列表
    protected $giftBagTable = 'gift_bag';
    protected $giftBagLogTable = 'gift_bag_log';
    protected $giftGiveTable = 'gift_give';

    protected $luckGiftPoolTable = 'luck_gift_pool';
    protected $luckGiftPoolConfigTable = 'luck_gift_pool_config';
    protected $luckGiftWhiteTable = 'luck_gift_white';
    protected $luckGiftLogTable = 'luck_gift_log';

    public $timestamps = false;
    protected $fillable = ['name', 'image', 'animate_resource','price','gift_sort','gift_label_id'];
    private $fields = ['gift_id','name', 'image', 'animate_resource','price','gift_sort','is_show','animate_resource_md5','gift_type','gift_label_id', 'is_special', 'classification', 'wealth_num', 'hot_num','ext_data'];
    protected $attributes = [
        'is_show' => 1,
        'gift_sort' => 0
    ];
    protected $primaryKey = 'gift_id';

    public function classificationConfig()
    {
        return $this->hasOne('App\Model\GiftClassificationConfig', 'gift_id', 'gift_id');
    }

    public function getList(Request $request){
        $page = $request->get('page', 0);
        $limit = $request->get('limit', 10);
        $gift_id = $request->get('gift_id', '');
        $gift_name = $request->get('gift_name', '');
        $gift_type = $request->get('gift_type', '');
        $minPrice = intval($request->get('min_price', 0));// 最低价格
        $maxPrice = intval($request->get('max_price', 0));// 最高价格
        $orderProp = $request->get('order_prop', '');// 排序字段
        $order = $request->get('order', '');// 升序or降序
        $orderProp = $orderProp ?: 'gift_id';
        $order = $order ?: 'desc';


        $where = [];
        if($gift_id != '') $where[] = ['gift_id', '=', $gift_id];
        if($gift_name != '') $where[] = ['name', 'like', "%{$gift_name}%"];
        if($gift_type != '') $where[] = ['gift_type', '=', $gift_type];
        if ($minPrice) {
            $where[] = ['price', '>=', $minPrice];
        }

        if ($maxPrice) {
            $where[] = ['price', '<=', $maxPrice];
        }

        $query = new GiftLibrary();
        // todo 搜索
        $list = $this->objToArray($query->with(['classificationConfig:gift_id,config'])->orderBy($orderProp, $order)
            ->where($where)
            ->paginate($limit, $this->fields, 'page', $page));
        foreach ($list['data'] as &$item) {
            $item['config'] = $item['classification_config'] ? $item['classification_config']['config'] : [];
            unset($item['classification_config']);
            $formatConfig = [];
            $itemConfig = $item['config'] ? json_decode($item['config'], true) : [];
            foreach ($itemConfig as $config) {
                if (isset($config['img'])) {
                    $config['fileList'] = [['name' => $config['img'], 'url' => build_image($config['img'])]];
                }

                if (isset($config['resource'])) {
                    $config['resourceList'] = [['name' => $config['resource'], 'url' => build_image($config['resource'])]];
                }

                if (isset($config['min_value'])) {
                    $config['min_value'] = intval($config['min_value']);
                }

                $formatConfig[] = $config;
            }

            $item['config'] = $formatConfig;

            if(!empty($item['ext_data']) && in_array($item['gift_type'], [9])) {
                $item['ext_data'] = json_decode($item['ext_data'], true);
            }else{
                $item['ext_data'] = [];
            }
        }
        return $list;
    }

    public function getGiftByGiftName(string $name){
        return self::where('name','LIKE',"{$name}%")->get();
    }


    /*
        * 添加
        * */
    public function createData($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/gift/create', $data, 'json', 'POST');
    }

    /*
         * 更新
         * */
    public function updateData($data)
    {
       return curl_request(getKkaudioApiUrl() . '/inner/gift/update', $data, 'json', 'POST');
    }


    /*
        * 删除
        * */
    public function removeData($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/gift/remove', $data, 'urlencoded', 'GET');
    }

    public function getGiftByIds($gift_ids)
    {
        return self::whereIn('gift_id', $gift_ids)->get(['gift_id','name', 'image'])->toArray();
    }

    /**
     * 获取礼物分类
     *
     * Created at 2021/12/30 18:02
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @return mixed
     */
    public function getGiftClassification()
    {
        return curl_request(getKkaudioApiUrl() . '/inner/gift/get_gift_classification', [], 'urlencoded', 'GET');
    }

    /**
     * 获取等级数据(财富、魅力、cp)
     *
     * Created at 2022/1/4 19:19
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @return mixed
     */
    public function getRankData($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/gift/get_rank_data', $data, 'urlencoded', 'GET');
    }

    //幸运礼物列表
    public function luckGiftList(Request $request)
    {
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        $gift_id = $request->input('gift_id');
        $gift_name = $request->get('gift_name', '');

        $query = DB::connection($this->connection)->table($this->table)->where('gift_type', 2);
        if(!empty($gift_id)) {
            $query = $query->where('gift_id', $gift_id);
        }
        if(!empty($gift_name)) {
            $query = $query->where('name', 'like', '%'.$gift_name.'%');
        }
        $result = $query->orderBy('gift_id', 'desc')->paginate($limit, $this->fields, 'page', $page);
        $result = objToArray($result);
        if(!empty($result['data'])) {
            foreach($result['data'] as $key=>$val) {
                $val['image'] = build_image($val['image']);
                $val['animate_resource'] = build_image($val['animate_resource']);

                $result['data'][$key] = $val;
            }
        }

        return $result;
    }

    //幸运礼物奖池列表
    public function luckGiftPoolList(Request $request)
    {
        $gift_id = $request->input('gift_id');
        if(empty($gift_id)) {
            return [];
        }

        $list = DB::connection($this->connection)->table($this->giftLuckPool_table)
            ->where('gift_id', $gift_id)
            ->get();
        $list = objToArray($list);

        if(!empty($list)) {
            $giftIds = array_column($list, 'gift_id');
            $giftList = DB::connection($this->connection)->table($this->table)->whereIn('gift_id', $giftIds)->get();
            $giftList = array_column(objToArray($giftList), null, 'gift_id');
            foreach($list as $key=>$val) {
                $val['gift_name'] = empty($giftList[$val['gift_id']]['name']) ? '' : $giftList[$val['gift_id']]['name'];

                $list[$key] = $val;
            }
        }

        return $list;
    }

    //设置幸运礼物奖池
    public function setLuckGiftPoll($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/setLuckGiftPoll', $data, 'json', 'POST');
        if(isset($res['code']) && $res['code']==0) {
            return [];
        }else{
            return [
                'code' => 50000,
                'msg' => empty($res['msg']) ? '失败' : $res['msg'],
                'data' => [],
            ];
        }
    }

    //送礼数据
    public function sendList($page, $limit, $startDate, $endDate, $isBag, $giftId){
        $where = function($q)use($startDate, $endDate, $isBag, $giftId) {
            $q->where('type',1);
            if(!empty($startDate)){
                $q->where('change_timestamp','>=',strtotime($startDate));
            }
            if(!empty($endDate)){
                $q->where('change_timestamp','<=',strtotime($endDate));
            }
            if(!empty($isBag)){
                $q->where('type',2);
            }
            if(!empty($giftId)){
                $giftIds = explode(',',$giftId);
                $q->whereIn('gift_id',$giftIds);
            }
        };
        $model = DB::connection($this->connection)
                ->table($this->giftStreamTable)
                ->selectRaw(DB::raw("date_format(FROM_UNIXTIME(change_timestamp),'%Y-%m-%d') as date,gift_id, sum(gift_num) as num,gift_price,SUM(gift_price*gift_num) as total,COUNT(distinct(from_user_id)) as send_people,type"))
                ->where($where)
                ->orderBy('change_timestamp','desc')
                ->groupBy('change_timestamp');
        $res = DB::connection($this->connection)->table(DB::raw("({$model->toSql()}) as other"))
            ->mergeBindings($model)
            ->selectRaw(DB::raw("date,gift_id, sum(num) as num,gift_price,SUM(total) as total,sum(send_people) as send_people,type"))
            ->groupBy('date','gift_id')
            ->paginate($limit,['*'],'page',$page);
        return $res;
    }

    //送礼详情表
    public function sendInfo($page, $limit, $startDate, $endDate, $sendUser, $toUser, $giftId){
        $where = function($q)use($startDate, $endDate, $sendUser, $toUser, $giftId) {
            if(!empty($startDate)){
                $q->where('change_timestamp','>=',strtotime($startDate));
            }
            if(!empty($endDate)){
                $q->where('change_timestamp','<=',strtotime($endDate));
            }
            if(!empty($giftId)){
                $giftIds = explode(',',$giftId);
                $q->whereIn('gift_id',$giftIds);
            }
            if(!empty($sendUser)){
                //uuid查询用户userId
                $sendUserIds = explode(',',$sendUser);
                $userIds = DB::connection($this->connection)->table($this->user)->whereIn('uuid',$sendUserIds)->get(['user_id']);
                $userIds = objToArray($userIds);
                $userIds = array_column($userIds,'user_id');
                $q->whereIn('from_user_id',$userIds);
            }
            if(!empty($toUser)){
                //uuid查询用户userId
                $toUserIds = explode(',',$toUser);
                $userIds = DB::connection($this->connection)->table($this->user)->whereIn('uuid',$toUserIds)->get(['user_id']);
                $userIds = objToArray($userIds);
                $userIds = array_column($userIds,'user_id');
                $q->whereIn('user_id',$userIds);
            }
        };
        $res = DB::connection($this->connection)
                ->table($this->giftStreamTable)
                ->select(DB::raw('FROM_UNIXTIME(change_timestamp) as date,user_id,from_user_id,gift_id,gift_name,gift_type,type,gift_num as gift_num,gift_price,gift_num*gift_price as total'))
                ->where($where)
                ->orderBy('change_timestamp','desc')
                ->paginate($limit,['*'],'page',$page);
        return $res;
    }

    //设置套盒礼物奖池
    public function setSetboxGiftPool($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/setSetboxGiftPool', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //获取套盒礼物奖池
    public function getSetboxGiftPool(Request $request)
    {
        $giftId = $request->input('gift_id');
        if(empty($giftId)) {
            return [
                'code' => 50000,
                'msg' => '参数错误',
                'data' => [],
            ];
        }

        $giftInfo = DB::connection($this->connection)->table($this->table)->where('gift_id', $giftId)->first();
        $giftInfo = objToArray($giftInfo);
        if(empty($giftInfo) || $giftInfo['gift_type']!=6) {
            return [
                'code' => 50000,
                'msg' => '这个礼物不是套盒礼物',
                'data' => [],
            ];
        }
        if(!empty($giftInfo['ext_data'])){
            $ext_data = json_decode($giftInfo['ext_data'], true);
            $giftList = DB::connection($this->connection)->table($this->table)->whereIn('gift_id', $ext_data)->select(['gift_id', 'name', 'image', 'price'])->get();
            $giftList = array_column(objToArray($giftList), null, 'gift_id');
        }else{
            $ext_data = [];
        }
        $list = [];
        foreach($ext_data as $val) {
            $item = [];
            $item['gift_id'] = $val;
            $item['name'] = empty($giftList[$val]['name']) ? '' : $giftList[$val]['name'];
            $item['image'] = empty($giftList[$val]['image']) ? '' : build_image($giftList[$val]['image']);
            $item['price'] = empty($giftList[$val]['price']) ? 0 : $giftList[$val]['price'];
            $list[] = $item;
        }

        return [
            'code' => 20000,
            'msg' => '成功',
            'data' => $list,
        ];
    }

    //彩蛋礼物配置概率列表
    public function colorGiftPool($page, $limit, $colorGiftId){

        $list = DB::connection($this->connection)->table($this->colorGifColorPoolTable)->where('gift_id',$colorGiftId)->paginate($limit,['*'],'page',$page);
        $list = objToArray($list);
        if(!empty($list['data'])){
            foreach ($list['data'] as &$v){
                $v['out_rate'] = $v['out_rate']/100;
            }
        }
        return $list;
    }

    //彩蛋礼物列表
    public function colorGiftList($page,$limit){
        $list = DB::connection($this->connection)->table($this->giftTable)->where('gift_type',5)->paginate($limit,['*'],'page',$page);
        $list = objToArray($list);
        if(!empty($list['data'])){
            foreach($list['data'] as &$v){
                $v['image'] = build_image($v['image']);
            }
        }
        
        return $list;
    }

    //彩蛋礼物奖池配置
    public function colorGiftPoolSet($gift_id, $name, $rate, $min_count, $max_count, $hours){
        $params = [
            'gift_id' => $gift_id,
            'name' => $name,
            'rate' => $rate,
            'min_count' => $min_count,
            'max_count' => $max_count,
            'hours' => $hours,
        ];
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/color_gift_pool_set', $params, 'urlencoded', 'POST');
        return curlResultHandle($res);
    }

    //彩蛋编辑奖池
    public function colorGiftEditPool($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/color_gift_pool_edit', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //查看目前奖池下对应有多少概率
    public function getPoolRateList($poolId){
        if(empty($poolId)) {
            return ['code'=>50001, 'data'=>[], 'msg'=>'参数错误,缺少奖池id'];
        }
        $res = DB::connection($this->connection)
            ->table($this->colorGiftPoolConfigTable)
            ->where('is_delete',0)
            ->where('pool_id',$poolId)
            ->distinct('rate_num')
            ->get(['rate_num']);
        $res = objToArray($res);
        $data = [];
        foreach($res as $v){
            $data[] = [
                'name' => '概率'.$v['rate_num'],
                'rate_num' => $v['rate_num']
            ];
        }
        
        if(empty($data)){
            $max = DB::connection($this->connection)
            ->table($this->colorGiftPoolConfigTable)
            ->selectRaw(DB::raw('MAX(rate_num) as rate_num'))
            ->where('pool_id',$poolId)
            ->first();
            $max = objToArray($max);
            $nowMax = (int)$max['rate_num'];
            $nextNum = $nowMax+1;
            $data[] = [
                'name' => '概率'.$nextNum,
                'rate_num' => $nextNum,
            ];
        }
        return ['code'=>20000, 'data'=>$data, 'msg'=>'ok'];
    }

    //新增奖池下概率配置
    public function addPoolRate($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/addPoolRate', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //删除概率配置
    public function colorGiftRateDel($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/colorGiftRateDel', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //彩蛋池配置礼物列表
    public function colorGiftPoolConfigList(Request $request)
    {
        $poolId = $request->input('pool_id');
        $rate_num = $request->input('rate_num',1);//要查询的概率
        if(empty($poolId)) {
            return ['code'=>50001, 'data'=>[], 'msg'=>'参数错误'];
        }

        $query = DB::connection($this->connection)
            ->table($this->colorGiftPoolConfigTable.' as a')
            ->leftJoin($this->giftTable.' as b' ,'a.gift_id','=','b.gift_id')
            ->where('a.pool_id', $poolId)
            ->where('a.is_delete',0)
            ->where('rate_num',$rate_num)
            ->select(['a.id','a.pool_id','a.item_no','a.gift_id','a.gift_num','b.name as gift_name','b.image as gift_image','a.out_rate','b.price as gift_price']);

        $list = $query->orderBy('a.item_no', 'asc')->get();
        $list = objToArray($list);

        return ['code'=>20000, 'data'=>$list, 'msg'=>'ok'];
    }

    //彩蛋池保存配置奖励
    public function colorGiftSavePoolConfig($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/colorGiftSavePoolConfig', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //彩蛋奖池开关
    public function colorGiftSetPoolStatus($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/colorGiftSetPoolStatus', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //彩蛋更新奖池
    public function colorGiftPoolReset($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/colorGiftPoolReset', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //彩蛋奖池剩余数量
    public function colorGiftPoolConfigNum($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/colorGiftPoolConfigNum', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //彩蛋礼物上限值配置列表
    public function colorGiftMaxList(){
        $res = DB::connection($this->connection)->table($this->colorGiftMaxConfigTable)->first();
        $res = objToArray($res);
        return $res;
    }

    //彩蛋礼物上线配置
    public function colorGiftPoolMaxSet($maxOut,$maxIn){
        $params = [
            'max_out' => $maxOut,
            'max_in' => $maxIn,
        ];
        return curl_request(getKkaudioApiUrl() . '/inner/gift/color_gift_max_set', $params, 'urlencoded', 'POST');
    }

    //彩蛋统计
    public function colorGiftData($page, $limit, $date_st, $date_ed){
        $model = DB::connection($this->connection)->table($this->colorGiftStream)->select(DB::raw("SUM(color_gift_price) as total,DATE_FORMAT(created_at,'%Y-%m-%d') as date"))->groupBy('created_at');
        if(!empty($date_st)) {
            $model = $model->where('created_at', '>=', $date_st);
        }
        if(!empty($date_ed)) {
            $model = $model->where('created_at', '<=', $date_ed);
        }
        $res = DB::connection($this->connection)->table(DB::raw("({$model->toSql()}) as other"))
            ->mergeBindings($model)
            ->selectRaw(DB::raw("date, sum(total) as allIn"))
            ->groupBy('date')

            ->paginate($limit,['*'],'page',$page);
        $res = objToArray($res);
        //返奖统计
        $awardModel = DB::connection($this->connection)->table($this->colorGiftStream)->select(DB::raw("SUM(award_gift_price*gift_num) as total,DATE_FORMAT(created_at,'%Y-%m-%d') as date"))->groupBy('created_at');
        if(!empty($date_st)) {
            $awardModel = $awardModel->where('created_at', '>=', $date_st);
        }
        if(!empty($date_ed)) {
            $awardModel = $awardModel->where('created_at', '<=', $date_ed);
        }
        $awardres = DB::connection($this->connection)->table(DB::raw("({$awardModel->toSql()}) as other"))
            ->mergeBindings($awardModel)
            ->selectRaw(DB::raw("date, sum(total) as allOut"))
            ->groupBy('date')
            ->get();
        $awardres = objToArray($awardres);
        $awardres = array_column($awardres,null,'date');
        foreach($res['data'] as &$v){
            $v['allOut'] = isset($awardres[$v['date']]) ? $awardres[$v['date']]['allOut'] : 0;
            $v['getMoney'] = $v['allIn'] - $v['allOut'];
            $v['rate'] = round(($v['allOut']*100) / $v['allIn'],2);
        }
        return $res;
    }

    //彩蛋礼物爆出记录
    public function colorGiftLog($page, $limit, $date_st, $date_ed, $user_id, $user_uuid){
        if(!empty($user_uuid)){
            $userInfo = DB::connection($this->connection)->table($this->user)->where('uuid',$user_uuid)->first();
            $userInfo = objToArray($userInfo);
            $user_id = empty($userInfo) ? 1 : $userInfo['user_id'];
        }

        $query = DB::connection($this->connection)->table($this->colorGiftStream);
        if(!empty($date_st)) {
            $query = $query->where('created_at', '>=', $date_st);
        }
        if(!empty($date_ed)) {
            $query = $query->where('created_at', '<=', $date_ed);
        }
        if(!empty($user_id)) {
            $query = $query->where('user_id', $user_id);
        }

        $res = $query
            ->orderBy('created_at','desc')
            ->paginate($limit,['*'],'page',$page);
        $res = objToArray($res);
        if(!empty($res['data'])){
            foreach($res['data'] as &$v){
                //送礼人信息
                $sendInfo = DB::connection($this->connection)->table($this->user)->where('user_id',$v['user_id'])->first();
                $sendInfo = objToArray($sendInfo);
                $v['send_user_name'] = $sendInfo['nickname'];//送礼人名称
                //收礼人信息
                $toInfo = DB::connection($this->connection)->table($this->user)->where('user_id',$v['to_user_id'])->first();
                $toInfo = objToArray($toInfo);
                $v['to_user_name'] = $toInfo['nickname'];//送礼人名称
                //获取彩蛋信息
                $colorGiftInfo = DB::connection($this->connection)->table($this->table)->where('gift_id',$v['color_id'])->first();
                $colorGiftInfo = objToArray($colorGiftInfo);
                $v['color_gift_name'] = $colorGiftInfo['name'];
                $v['cost_diamond'] = $colorGiftInfo['price'];
                $v['reward_money'] = $colorGiftInfo['price'] - $v['award_gift_price'];
            }
        }
        return $res;
    }

    //新增概率彩蛋banner
    public function colorGiftRateAddBanner($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/colorGiftRateAddBanner', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //获取概率banner
    public function colorGiftRateBanner($data){
        if(empty($data['pool_id']) || empty($data['rate_num'])){
            return ['code'=>50001, 'data'=>[], 'msg'=>'参数错误,缺少奖池id,概率id'];
        }
        $res = DB::connection($this->connection)
                ->table($this->colorGiftPoolRateBannerTable)
                ->where('pool_id',$data['pool_id'])
                ->where('rate_num',$data['rate_num'])
                ->first();
        $res = objToArray($res);
        if(!empty($res)){
            $res['bulid_img_url'] = build_image($res['img_url']);
        }
        return ['code'=>20000, 'data'=>$res, 'msg'=>'ok'];
    }

    //彩蛋用户汇总统计数据
    public function colorGiftStat($page, $limit, $date_st, $date_ed, $user_id, $user_uuid){
        if(!empty($user_uuid)){
            $userInfo = DB::connection($this->connection)->table($this->user)->where('uuid',$user_uuid)->first();
            $userInfo = objToArray($userInfo);
            $user_id = empty($userInfo) ? 1 : $userInfo['user_id'];
        }

        //产出
        $query = DB::connection($this->connection)->table($this->colorGiftStream)
            ->selectRaw('user_id, SUM(award_gift_price*gift_num) as allOut');
        if(!empty($date_st)) {
            $query = $query->where('created_at', '>=', date("Y-m-d H:i:s", strtotime($date_st)));
        }
        if(!empty($date_ed)) {
            $query = $query->where('created_at', '<=', date("Y-m-d H:i:s", strtotime($date_ed)));
        }
        if(!empty($user_id)) {
            $query = $query->where('user_id', $user_id);
        }
        $data = $query->groupBy('user_id')->orderBy('user_id', 'desc')->paginate($limit, ['*'], 'page', $page);
        $data = objToArray($data);

        //汇总数据 产出
        $query2 = DB::connection($this->connection)->table($this->colorGiftStream)
            ->selectRaw('count(DISTINCT user_id) as user_num, SUM(award_gift_price*gift_num) as allOut');
        if(!empty($date_st)) {
            $query2 = $query2->where('created_at', '>=', date("Y-m-d H:i:s", strtotime($date_st)));
        }
        if(!empty($date_ed)) {
            $query2 = $query2->where('created_at', '<=', date("Y-m-d H:i:s", strtotime($date_ed)));
        }
        if(!empty($user_id)) {
            $query2 = $query2->where('user_id', $user_id);
        }
        $data2 = $query2->first();
        $data2 = objToArray($data2);
        $data2['user_num'] = empty($data2['user_num']) ? 0 : $data2['user_num'];
        $data2['allOut'] = empty($data2['allOut']) ? 0 : $data2['allOut'];

        //投入
        $query3 = DB::connection($this->connection)->table($this->colorGiftStream)
            ->selectRaw('user_id, SUM(color_gift_price) as allIn');
        if(!empty($date_st)) {
            $query3 = $query3->where('created_at', '>=', date("Y-m-d H:i:s", strtotime($date_st)));
        }
        if(!empty($date_ed)) {
            $query3 = $query3->where('created_at', '<=', date("Y-m-d H:i:s", strtotime($date_ed)));
        }
        if(!empty($user_id)) {
            $query3 = $query3->where('user_id', $user_id);
        }
        $data3 = $query3->groupBy('user_id')->orderBy('user_id', 'desc')->paginate($limit, ['*'], 'page', $page);
        $data3 = objToArray($data3);

        //汇总数据 投入
        $query4 = DB::connection($this->connection)->table($this->colorGiftStream)
            ->selectRaw('count(DISTINCT user_id) as user_num, SUM(color_gift_price) as allIn');
        if(!empty($date_st)) {
            $query4 = $query4->where('created_at', '>=',  date("Y-m-d H:i:s", strtotime($date_st)));
        }
        if(!empty($date_ed)) {
            $query4 = $query4->where('created_at', '<=', date("Y-m-d H:i:s", strtotime($date_ed)));
        }
        if(!empty($user_id)) {
            $query4 = $query4->where('user_id', $user_id);
        }
        $data4 = $query4->first();
        $data4 = objToArray($data4);
        $data4['user_num'] = empty($data4['user_num']) ? 0 : $data4['user_num'];
        $data4['allIn'] = empty($data4['allIn']) ? 0 : $data4['allIn'];

        $userIds = array_unique(array_merge(array_column($data['data'], 'user_id'), array_column($data3['data'], 'user_id')));
        $userList = DB::connection($this->connection)->table($this->user)->whereIn('user_id', $userIds)->select('user_id','nickname','uuid')->get();
        $userList = array_column(objToArray($userList), null, 'user_id');

        //数据整理
        $result = ['list'=>[], 'all'=>[], 'total'=>0];
        $result['total'] = max($data['total'], $data3['total']);
        $result['all']['user_num'] = max($data2['user_num'], $data4['user_num']);
        $result['all']['allOut'] = $data2['allOut'];
        $result['all']['allIn'] = $data4['allIn'];
        $result['all']['output_ratio'] = ($result['all']['allIn']>0) ? round(($result['all']['allOut']/$result['all']['allIn'])*100,4) : '0.0000';
        $result['all']['profit_loss'] = $result['all']['allOut'] - $result['all']['allIn'];

        $data = array_column($data['data'], null, 'user_id');
        $data3 = array_column($data3['data'], null, 'user_id');

        foreach($userIds as $userId) {
            $item = [];
            $item['user_id'] = $userId;
            $item['nickname'] = empty($userList[$userId]['nickname']) ? '' : $userList[$userId]['nickname'];
            $item['uuid'] = empty($userList[$userId]['uuid']) ? '' : $userList[$userId]['uuid'];
            $item['allOut'] = empty($data[$userId]['allOut']) ? 0 : $data[$userId]['allOut'];
            $item['allIn'] = empty($data3[$userId]['allIn']) ? 0 : $data3[$userId]['allIn'];
            $item['output_ratio'] = ($item['allIn']>0) ? round(($item['allOut']/$item['allIn'])*100,4) : '0.0000';
            $item['profit_loss'] = $item['allOut'] - $item['allIn'];

            $result['list'][] = $item;
        }

        return $result;
    }

    //查看对应彩蛋下开启奖池中的配置礼物信息
    public function getColorGiftPoolConfig($colorGiftId){
        $openPool = DB::connection($this->connection)
                    ->table($this->colorGifColorPoolTable)
                    ->where('is_open',1)
                    ->where('gift_id',$colorGiftId)
                    ->get();
        $openPool = objToArray($openPool);
        if(empty($openPool)){
            return [];
        }
        $openPoolIds = array_column($openPool,'id');
        //查询对应奖池下配置的所有概率的礼物信息
        $poolRateGiftList = DB::connection($this->connection)
                    ->table($this->colorGiftPoolConfigTable)
                    ->whereIn('pool_id',$openPoolIds)
                    ->where('is_delete',0)
                    ->distinct('gift_id')
                    ->get('gift_id');
        $poolRateGiftList = objToArray($poolRateGiftList);
        $poolRateGiftIds = array_column($poolRateGiftList,'gift_id');
        //获取礼物信息
        $giftInfos = DB::connection($this->connection)
                    ->table($this->giftTable)
                    ->whereIn('gift_id',$poolRateGiftIds)
                    ->get(['gift_id','name','price']);
        return $giftInfos;
    }

    //新增彩蛋抽奖用户白名单
    public function colorGiftWhiteAdd($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/colorGiftWhiteAdd', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //编辑彩蛋白名单
    public function colorWhiteEdit($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/colorWhiteEdit', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //删除彩蛋用户白名单
    public function colorWhiteDel($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/colorWhiteDel', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //获取彩蛋白名单用户列表
    public function colorWhiteList($page, $limit, $user_id, $status, $start_time, $end_time){
        $where = function($q)use($user_id, $status, $start_time, $end_time) {
            $q->where('white.is_deleted',0);
           
            if(!empty($user_id)){
                $q->where('white.user_id',$user_id);
            }
            if(is_numeric($status)){
                $q->where('white.status', $status);
            }
            if(!empty($start_time)){
                $start_time = strtotime($start_time);
                $start_time = date('Y-m-d',$start_time).' 00:00:00';
                $q->where('white.updated_at','>=',$start_time);
            }
            if(!empty($end_time)){
                $end_time = strtotime($end_time);
                $end_time = date('Y-m-d',$end_time).' 23:59:59';
                $q->where('white.updated_at','<=',$end_time);
            }
        };
        $data = DB::connection($this->connection)
                ->table($this->colorGiftWhiteTable.' as white')
                ->leftJoin($this->user.' as user','user.user_id','white.user_id')
                ->leftJoin($this->giftTable.' as gift','gift.gift_id','white.color_gift_id')
                ->leftJoin($this->giftTable.' as gifts','gifts.gift_id','white.pop_gift_id')
                ->where($where)
                ->orderBy('white.id','DESC')
                ->paginate($limit,['white.id','white.user_id','user.uuid','user.nickname','white.color_gift_id','gift.name','white.pop_gift_id','gifts.name as pop_name','white.delete_pop','white.status','white.updated_at'],'page',$page);

        $data = objToArray($data);
        return $data;
    }

    //新幸运礼物新增奖池
    public function luckGiftAddPool($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/luckGiftAddPool', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //新幸运礼物编辑奖池
    public function luckGiftEditPool($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/luckGiftEditPool', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //新幸运礼物新增奖池配置
    public function luckGiftAddPoolConfig($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/luckGiftAddPoolConfig', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //新幸运礼物编辑奖池配置
    public function luckGiftEditPoolConfig($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/luckGiftEditPoolConfig', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //新幸运礼物删除奖池配置
    public function luckGiftDelPoolConfig($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/luckGiftDelPoolConfig', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //新幸运礼物更新奖池缓存
    public function luckGiftPoolReset($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/luckGiftPoolReset', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //新幸运礼物设置奖池开启/关闭
    public function luckGiftSetPoolStatus($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/luckGiftSetPoolStatus', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //新幸运礼物奖池配置剩余数量
    public function luckGiftPoolConfigNum($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/luckGiftPoolConfigNum', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //新幸运礼物新增白名单
    public function luckGiftAddWhite($data, $user){
        $data['admin_id'] = $user['id'];
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/luckGiftAddWhite', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //新幸运礼物删除白名单
    public function luckGiftDelWhite($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/luckGiftDelWhite', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //新幸运礼物奖池列表
    public function luckGiftPoolListV2(Request $request)
    {
        $status = $request->input('status');

        $query = DB::connection($this->connection)->table($this->luckGiftPoolTable);
        if(!empty($status)) {
            $query = $query->where('status', $status);
        }

        $list = $query->get();
        $list = objToArray($list);

        return ['code'=>20000, 'data'=>$list, 'msg'=>'ok'];
    }

    //新幸运礼物奖池配置列表
    public function luckGiftPoolConfigList(Request $request)
    {
        $pool_id = $request->input('pool_id');

//        $query = DB::connection($this->connection)->table($this->luckGiftPoolConfigTable)
//            ->where('is_delete', 0)->where('pool_id', $pool_id);
        $query = DB::connection($this->connection)->table($this->luckGiftPoolConfigTable.' as a')
            ->leftJoin($this->luckGiftPoolTable.' as b' ,'a.pool_id','=','b.id')
            ->where('a.is_delete', 0)->where('a.pool_id', $pool_id);


        $list = $query->get();
        $list = objToArray($list);

        return ['code'=>20000, 'data'=>$list, 'msg'=>'ok'];
    }

    //新幸运礼物白名单列表
    public function luckGiftWhiteList(Request $request, $adminUser)
    {
        $user_id = $request->input('user_id', 0);
        $uuid = $request->input('uuid', 0);
        $status = $request->input('status', 0);

        $query = DB::connection($this->connection)
            ->table($this->luckGiftWhiteTable.' as a')
            ->leftJoin($this->user.' as b' ,'a.user_id','=','b.user_id')
            ->select(['a.id','a.user_id','a.diamond_num','a.status','a.log_id'
                    ,'b.uuid','b.nickname'])
            ->where('a.is_delete', 0);
        if($adminUser->id != 18) {
            $query = $query->where('a.admin_id', '<>', 18);
        }
        if(!empty($user_id)) {
            $query = $query->where('a.user_id', $user_id);
        }
        if(!empty($uuid)) {
            $query = $query->where('b.uuid', $uuid);
        }
        if($status >= 0) {
            $query = $query->where('a.status', $status);
        }
        $list = $query->orderBy('a.id', 'desc')->get();
        $list = objToArray($list);

        return ['code'=>20000, 'data'=>$list, 'msg'=>'ok'];
    }

    //新幸运礼物抽奖明细列表
    public function luckGiftDrawList(Request $request)
    {
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');
        $user_id = $request->input('user_id');
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);

        $query = DB::connection($this->connection)->table($this->luckGiftLogTable)
            ->select(['id', 'user_id', 'gift_id', 'gift_num', 'u_diamond_num', 'r_diamond_num', 'created_at']);
        if(!empty($date_st)) {
            $query = $query->where('created_at', '>=', date("Y-m-d H:i:s", strtotime($date_st)));
        }
        if(!empty($date_ed)) {
            $query = $query->where('created_at', '<=', date("Y-m-d H:i:s", strtotime($date_ed)));
        }
        if(!empty($user_id)) {
            $query = $query->where('user_id', $user_id);
        }
        $data = $query->orderBy('id', 'desc')->paginate($limit, ['*'], 'page', $page);
        $data = objToArray($data);

        $result = ['list'=>[], 'total'=>0];
        if(!empty($data['data'])) {
            $result['total'] = $data['total'];

            $userIds = array_column($data['data'], 'user_id');
            $userList = DB::connection($this->connection)->table($this->user)->whereIn('user_id', $userIds)->select('user_id','nickname','uuid')->get();
            $userList = array_column(objToArray($userList), null, 'user_id');

            $giftIds = array_column($data['data'], 'gift_id');
            $giftList = DB::connection($this->connection)->table($this->giftTable)->whereIn('gift_id', $giftIds)->select(['gift_id','name','image','price'])->get();
            $giftList = array_column(objToArray($giftList), null, 'gift_id');

            $list = [];
            foreach($data['data'] as $val) {
                $val['giftName'] = empty($giftList[$val['gift_id']]['name']) ? '' : $giftList[$val['gift_id']]['name'];
                $val['nickname'] = empty($userList[$val['user_id']]['nickname']) ? '' : $userList[$val['user_id']]['nickname'];
                $val['uuid'] = empty($userList[$val['user_id']]['uuid']) ? '' : $userList[$val['user_id']]['uuid'];
                //主播分成
                $val['anchor_num'] = $val['u_diamond_num']*0.01;
                //平台流入
                $val['platform_num'] = $val['u_diamond_num']*0.99;
                //盈亏
                $val['profit_loss'] = $val['platform_num'] - $val['r_diamond_num'];
                //返奖率
                $val['output_ratio'] = ($val['u_diamond_num']>0) ? round(($val['r_diamond_num']/($val['u_diamond_num']*0.99))*100,4) : '0.0000';
                $list[] = $val;
            }

            $result['list'] = $list;
        }

        return ['code'=>20000, 'data'=>$result, 'msg'=>'ok'];
    }

    //新幸运礼物抽奖每日统计
    public function luckGiftDayStatistic(Request $request)
    {
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        if(empty($date_st)) $date_st = '2024-02-01';
        if(empty($date_ed)) $date_ed = '2124-01-01';
        $date_st = date("Ymd", strtotime($date_st));
        $date_ed =  date("Ymd", strtotime($date_ed));

        $query = DB::connection($this->connection)->table($this->luckGiftLogTable)
            ->selectRaw('ymd, count(DISTINCT user_id) as user_num, sum(u_diamond_num) as u_diamond_num, sum(r_diamond_num) as r_diamond_num');
        $query = $query->where('ymd', '>=', $date_st);
        $query = $query->where('ymd', '<=', $date_ed);
        $data = $query->groupBy('ymd')->orderBy('ymd', 'desc')->paginate($limit, ['*'], 'page', $page);
        $data = objToArray($data);

        $result = ['list'=>[], 'total'=>0];
        if(!empty($data['data'])) {
            $result['total'] = $data['total'];

            $list = [];
            foreach($data['data'] as $val) {
                //主播分成
                $val['anchor_num'] = $val['u_diamond_num']*0.01;
                //平台流入
                $val['platform_num'] = $val['u_diamond_num']*0.99;
                //盈亏
                $val['profit_loss'] = $val['platform_num'] - $val['r_diamond_num'];
                //返奖率
                $val['output_ratio'] = ($val['u_diamond_num']>0) ? round(($val['r_diamond_num']/($val['u_diamond_num']*0.99))*100,4) : '0.0000';

                $list[] = $val;
            }

            $result['list'] = $list;
        }

        return ['code'=>20000, 'data'=>$result, 'msg'=>'ok'];
    }

    //新幸运礼物抽奖用户统计
    public function luckGiftUserStatistic(Request $request)
    {
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');
        $user_id = $request->input('user_id');
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);

        $query = DB::connection($this->connection)->table($this->luckGiftLogTable)
            ->selectRaw('user_id, sum(u_diamond_num) as u_diamond_num, sum(r_diamond_num) as r_diamond_num');
        if(!empty($date_st)) {
            $query = $query->where('created_at', '>=', date("Y-m-d H:i:s", strtotime($date_st)));
        }
        if(!empty($date_ed)) {
            $query = $query->where('created_at', '<=', date("Y-m-d H:i:s", strtotime($date_ed)));
        }
        if(!empty($user_id)) {
            $query = $query->where('user_id', $user_id);
        }
        $data = $query->groupBy('user_id')->orderBy('user_id', 'desc')->paginate($limit, ['*'], 'page', $page);
        $data = objToArray($data);

        //汇总数据
        $query2 = DB::connection($this->connection)->table($this->luckGiftLogTable)
            ->selectRaw('count(DISTINCT user_id) as user_num, sum(u_diamond_num) as u_diamond_num, sum(r_diamond_num) as r_diamond_num');
        if(!empty($date_st)) {
            $query2 = $query2->where('created_at', '>=', date("Y-m-d H:i:s", strtotime($date_st)));
        }
        if(!empty($date_ed)) {
            $query2 = $query2->where('created_at', '<=', date("Y-m-d H:i:s", strtotime($date_ed)));
        }
        $data2 = $query2->first();
        $data2 = objToArray($data2);
        $data2['user_num'] = empty($data2['user_num']) ? 0 : $data2['user_num'];
        $data2['u_diamond_num'] = empty($data2['u_diamond_num']) ? 0 : $data2['u_diamond_num'];
        $data2['r_diamond_num'] = empty($data2['r_diamond_num']) ? 0 : $data2['r_diamond_num'];
        $data2['output_ratio'] = ($data2['u_diamond_num']>0) ? round(($data2['r_diamond_num']/($data2['u_diamond_num']*0.99))*100,4) : '0.0000';
        //主播分成
        $data2['anchor_num'] = $data2['u_diamond_num']*0.01;
        //平台流入
        $data2['platform_num'] = $data2['u_diamond_num']*0.99;
        //盈亏
        $data2['profit_loss'] = $data2['r_diamond_num'] - $data2['platform_num'];

        $result = ['list'=>[], 'all'=>$data2, 'total'=>0];
        if(!empty($data['data'])) {
            $result['total'] = $data['total'];

            $userIds = array_column($data['data'], 'user_id');
            $userList = DB::connection($this->connection)->table($this->user)->whereIn('user_id', $userIds)->select('user_id','nickname','uuid')->get();
            $userList = array_column(objToArray($userList), null, 'user_id');

            $list = [];
            foreach($data['data'] as $key=>$val) {
                $val['nickname'] = empty($userList[$val['user_id']]['nickname']) ? '' : $userList[$val['user_id']]['nickname'];
                $val['uuid'] = empty($userList[$val['user_id']]['uuid']) ? '' : $userList[$val['user_id']]['uuid'];
                //主播分成
                $val['anchor_num'] = $val['u_diamond_num']*0.01;
                //平台流入
                $val['platform_num'] = $val['u_diamond_num']*0.99;
                //盈亏
                $val['profit_loss'] = $val['r_diamond_num'] - $val['platform_num'];
                //返奖率
                $val['output_ratio'] = ($val['u_diamond_num']>0) ? round(($val['r_diamond_num']/($val['u_diamond_num']*0.99))*100,4) : '0.0000';

                $list[$key] = $val;
            }

            $result['list'] = $list;
        }

        return ['code'=>20000, 'data'=>$result, 'msg'=>'ok'];
    }


    //铭牌列表
    public function nameplateList(Request $request)
    {
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        $nameplate_id = $request->input('nameplate_id', 0);
        $nameplate_name = $request->input('nameplate_name', '');

        $query = DB::connection($this->connection)->table($this->nameplateTable)->where('is_delete', 0)->orderBy('id', 'desc');
        if(!empty($nameplate_id)) {
            $query = $query->where('id', $nameplate_id);
        }
        if(!empty($nameplate_name)) {
            $query = $query->where('nameplate_name', 'like', '%'.$nameplate_name.'%');
        }

        $result = $query->paginate($limit, ['*'], 'page', $page);
        $result = objToArray($result);

        if(!empty($result['data'])) {
            foreach($result['data'] as $key=>$val) {
                $val['nameplate_img'] = build_image($val['nameplate_img']);
                $val['nameplate_resource'] = build_image($val['nameplate_resource']);

                $result['data'][$key] = $val;
            }
        }
        $result = ['data'=>$result['data'], 'total'=>$result['total']];

        return $result;
    }

    //礼物背包流水列表
    public function giftBagLogList(Request $request)
    {
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        $user_id = $request->input('user_id', 0);
        $time_st = $request->input('time_st', '');
        $time_et = $request->input('time_et', '');
        $platform_type = $request->input('platform_type', 0);

        $query = DB::connection($this->connection)->table($this->giftBagLogTable.' as a')
            ->leftJoin($this->giftTable.' as b', "a.gift_id", "=", "b.gift_id")
            ->orderBy('a.id', 'desc')
            ->select(['a.*','b.name as gift_name','b.gift_type']);
        if(!empty($user_id)) {
            $query = $query->where('a.user_id', $user_id);
        }
        if(!empty($time_st)) {
            $time_st = date("Y-m-d H:i:s", strtotime($time_st));
            $query = $query->where('a.create_time', '>=', $time_st);
        }
        if(!empty($time_et)) {
            $time_et = date("Y-m-d H:i:s", strtotime($time_et));
            $query = $query->where('a.create_time', '<=', $time_et);
        }
        if(!empty($platform_type)) {
            $query = $query->where('a.platform_type', $platform_type);
        }

        $result = $query->paginate($limit, ['*'], 'page', $page);
        $result = objToArray($result);

        if(!empty($result['data'])) {
            $userIds = array_merge(array_column($result['data'], 'user_id'), array_column($result['data'], 'to_user_id'));
            $userList = DB::connection($this->connection)->table($this->user)->whereIn('user_id', $userIds)->get();
            $userList = array_column(objToArray($userList), null, 'user_id');

            $platformTypeList = $this->bagGiftPlatformType();
            $platformTypeList = array_column($platformTypeList['data'], 'name', 'platform_type');

            foreach($result['data'] as $key=>$val) {
                $val['nickname'] = empty($userList[$val['user_id']]['nickname']) ? '' : $userList[$val['user_id']]['nickname'];
                $val['uuid'] = empty($userList[$val['user_id']]['uuid']) ? '' : $userList[$val['user_id']]['uuid'];

                $val['to_nickname'] = empty($userList[$val['to_user_id']]['nickname']) ? '' : $userList[$val['to_user_id']]['nickname'];
                $val['to_uuid'] = empty($userList[$val['to_user_id']]['uuid']) ? '' : $userList[$val['to_user_id']]['uuid'];

                $val['platform_type_name'] = empty($platformTypeList[$val['platform_type']]) ? '' : $platformTypeList[$val['platform_type']];

                $result['data'][$key] = $val;
            }
        }
        $result = ['data'=>$result['data'], 'total'=>$result['total']];

        return $result;
    }

    //用户礼物背包列表
    public function giftBagList(Request $request)
    {
        $result = ['data'=>[], 'total'=>0];

        do {
            $user_id = $request->input('user_id', 0);
            if(empty($user_id)) {
                break;
            }

            $query = DB::connection($this->connection)->table($this->giftBagTable.' as a')
                ->leftJoin($this->giftTable.' as b', "a.gift_id", "=", "b.gift_id")
                ->orderBy('a.id', 'desc')
                ->select(['a.*','b.name as gift_name','b.gift_type','b.price as gift_price'])
                ->where('a.user_id', $user_id)
                ->where('a.avail', '>', 0);
            $result = $query->get();
            $result = objToArray($result);
            if(!empty($result)) {
                foreach($result as $key=>$val) {
                    $val['total_price'] = $val['avail'] * $val['gift_price'];

                    $result[$key] = $val;
                }
            }
            $result = ['data'=>$result, 'total'=>count($result)];
        } while (false);

        return $result;
    }

    //背包礼物来源类型
    public function bagGiftPlatformType(){
        $res = curl_request(getKkaudioApiUrl() . '/inner/gift/bagGiftPlatformType', [], 'urlencoded', 'GET');
        return curlResultHandle($res);
    }

    public function giftGiveHistory(Request $request, $adminUser)
    {
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);

        $query = DB::connection('mysql')->table($this->giftGiveTable.' as a')
//            ->leftJoin($this->giftTable.' as b', "a.gift_id", "=", "b.gift_id")
//            ->leftJoin($this->user.' as c', "a.user_id", "=", "c.user_id")
//            ->select(['a.*','b.name as gift_name','b.price as gift_price', 'c.uuid as uuid', 'c.nickname as nickname'])
            ->select(['a.*'])
            ->where('is_delete', '0');

        if($adminUser->id != 18) {
            $query = $query->where('a.admin_id', '<>', 18);
        }

        $list = $query->orderBy('id', 'desc')->paginate($limit, ['*'], 'page', $page);
        $list = objToArray($list);

        if(!empty($list['data'])){
            foreach($list['data'] as $k => $v){
                $giftInfo = DB::connection($this->connection)
                    ->table($this->giftTable)
                    ->where('gift_id',$v['gift_id'])
                    ->first(['gift_id','name','price']);
                $giftInfo = objToArray($giftInfo);
                $userInfo = DB::connection($this->connection)
                    ->table($this->user)
                    ->where('user_id',$v['user_id'])
                    ->first(['user_id','uuid','nickname']);
                $userInfo = objToArray($userInfo);
                $v['gift_name'] = $giftInfo['name'];
                $v['gift_price'] = $giftInfo['price'];
                $v['uuid'] = $userInfo['uuid'];
                $v['nickname'] = $userInfo['nickname'];

                $v['cur_admin_id'] = $adminUser->id;

                $list['data'][$k] = $v;
            }
        }

        return $list;
    }

    //后台ip白名单新增
    public function giftGiveAdd($params, $admin){
        unset($params['id']);

        $res = [
            'code' => 0,
            'data' => [],
            'msg' => '成功',
        ];
        if(empty($params['user_id']) || empty($params['gift_id']) || empty($params['number'])) {
            $res['code'] = 1;
            $res['msg'] = 'param empty';
            return $res;
        }
        $data['user_id'] = $params['user_id'];
        $data['gift_id'] = $params['gift_id'];
        $data['number'] = $params['number'];
        $data['remark'] = $params['remark'];
        $data['admin_id'] = $admin['id'];
        $data['admin_name'] = $admin['name'];
        $data['created_at'] = $data['updated_at'] = date('Y-m-d H:i:s', time());

        DB::beginTransaction();

        try{
            DB::connection('mysql')->table($this->giftGiveTable)->insertGetId($data);
            $this->inc($params['user_id'], 0, $params['gift_id'], $params['number'], 5001);

            DB::commit();
        }catch (\Exception $e) {
            DB::rollBack();
            $res['code'] = 1;
            $res['msg'] = $e->getMessage();
        }

        return $res;
    }

    //后台ip白名单删除
    public function giftGiveDel($params){
        $res = [
            'code' => 0,
            'data' => [],
            'msg' => '成功',
        ];
        if(empty($params['id'])) {
            $res['code'] = 1;
            $res['msg'] = 'id empty';
            return $res;
        }
        DB::connection('mysql')->table($this->giftGiveTable)->where('id', '=', $params['id'])->update(['is_delete' => 1]);
        return $res;
    }

    /**
     * 变更背包礼物
     * @param int $userId  用户ID
     * @param int $toUserId  获取礼物用户ID，获得礼物设置为0
     * @param int $giftId 礼物ID
     * @param int $change 变更礼物的数量 送礼物时为负数
     * @param int $platformType 来源类型 枚举在 bagGiftPlatformType()
     *
     */
    public function inc($userId, $toUserId, $giftId, $change, $platformType=0, $dataId=0)
    {
        // 此处执行标识
        $flag = true;

        // 更新背包剩余数
        $increment = DB::connection($this->connection)->table($this->giftBagTable)
            ->where('user_id', '=', $userId)
            ->where('gift_id', '=', $giftId)
            ->increment('avail', $change, ['update_timestamp' => time()]);

        if (!$increment) {
            // 创建背包默认数据
            $insertBag = DB::connection($this->connection)->table($this->giftBagTable)->insert([
                'user_id' => $userId,
                'gift_id' => $giftId,
                'avail' => $change,
                'create_timestamp' => time(),
                'update_timestamp' => time()
            ]);
            if (!$insertBag) {
                $flag = false;
            }
        }

        if ($flag) {
            // 创建背包日志
            $insertBagLog = DB::connection($this->connection)->table($this->giftBagLogTable)->insert([
                'user_id' => $userId,
                'gift_id' => $giftId,
                'to_user_id' => $toUserId,
                'change' => $change,
                'avail' => 0,
                'platform_type' => $platformType,
                'data_id' => $dataId,
                'create_timestamp' => time()
            ]);
            if (!$insertBagLog) {
                $flag = false;
            }
        }

        return $flag;
    }

}
